<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item prop="userName">
              <el-input v-model="searchForm.userName" :clearable="true" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item prop="nickName">
              <el-input v-model="searchForm.nickName" :clearable="true" placeholder="用户昵称"></el-input>
            </el-form-item>
            <el-form-item prop="phone">
              <el-input v-model="searchForm.phone" :clearable="true" placeholder="手机号"></el-input>
            </el-form-item>
            <el-form-item prop="userRole">
              <el-select v-model="searchForm.userRole" :clearable="true" placeholder="请选择用户角色">
                <el-option key="1" label="管理员" :value="1"></el-option>
                <el-option key="2" label="客户" :value="2"></el-option>
                <el-option key="3" label="商户" :value="3"></el-option>
                <el-option key="4" label="服务员" :value="4"></el-option>
                <el-option key="5" label="业务员" :value="5"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="isLogin">
              <el-select v-model="searchForm.isLogin" :clearable="true" placeholder="请选择登陆状态">
                <el-option key="1" label="在线" value="1"></el-option>
                <el-option key="0" label="离线" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="state">
              <el-select v-model="searchForm.state" :clearable="true" placeholder="请选择账号状态">
                <el-option key="1" label="启用" :value="1"></el-option>
                <el-option key="0" label="禁用" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <!--<el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()"
            size="mini">新增管理员</el-button>-->
        </div>
      </el-col>
    </el-row>
    <el-row ref="tableRow">
      <el-table :data="tableList" :fit="true">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column show-overflow-tooltip prop="userName" label="用户名" width="200"></el-table-column>
        <el-table-column show-overflow-tooltip prop="nickName" label="用户昵称" width="200"></el-table-column>
        <el-table-column show-overflow-tooltip prop="phone" label="手机号" width="150"></el-table-column>
        <el-table-column label="用户角色" align="center" width="150">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" :type="formatUserRoles(scope.row.userRole)">
                {{ formatUserRole(scope.row.userRole) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="登陆状态" align="center" width="120">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="plain" :type="formatLogins(scope.row.isLogin)">
                {{ formatLogin(scope.row.isLogin) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="启用状态" align="center" width="120">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="dark" :type="formatStates(scope.row.state)">
                {{ formatState(scope.row.state) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="loginOutTime" label="上次登录退出时间" align="center"></el-table-column>
        <el-table-column prop="loginTime" label="此次登录时间" align="center"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-row>
              <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
              <el-dropdown trigger="click" size="small">
                <el-button type="primary"><i class="fa fa-list-ul"></i>更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-has="permissionResetPwd" v-if="scope.row.userRole != 2" @click.native="handleClickResetPass(scope.row)">重置密码</el-dropdown-item>
                  <!--<el-dropdown-item v-has="permissionEdit"
                    @click.native="handleClickEditor(scope.row)">编辑</el-dropdown-item>-->
                  <el-dropdown-item v-has="permissionUpStatus" @click.native="handleIsDisable(scope.row)">{{ scope.row.state === 0 ? '启用' : '禁用' }}</el-dropdown-item>
                  <el-dropdown-item v-has="permissionDelete" @click.native="handleClickDelete(scope.row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>
  </div>
</template>
<script>
import * as message from '@/constants/message';
import { FORMAT_DATE_YYYY_MM_DD } from '@/constants/constants';
import AuthApi from '@/api/system/auth';
export default {
  name: 'UserManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      searchForm: {
        userName: '',
        nickName: '',
        phone: '',
        userRole: '',
        isLogin: '',
        state: '',
      },
      tableList: [],

      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      permissionCheck: 'SYSTEM_MANAGER_SYS_USER_LIST_SEE',
      permissionAdd: 'SYSTEM_MANAGER_SYS_USER_LIST_ADD',
      permissionEdit: 'SYSTEM_MANAGER_SYS_USER_LIST_EDIT',
      permissionUpStatus: 'SYSTEM_MANAGER_SYS_USER_LIST_STATE',
      permissionDelete: 'SYSTEM_MANAGER_SYS_USER_LIST_DELETE',
      permissionResetPwd: 'SYSTEM_MANAGER_SYS_USER_LIST_RESET',
    };
  },
  components: {},
  created() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    if (this.$route.meta.keepAlive) {
      this.listTable();
    }
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      this.listTable();
      this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    formatTime(row, column, cellValue) {
      return this.$Utils.formatDate(cellValue, FORMAT_DATE_YYYY_MM_DD);
    },
    formatSex(row, column, cellValue) {
      return cellValue === 1 ? '男' : '女';
    },
    formatUserRole(cellValue) {
      if (cellValue === 1) {
        return '管理员';
      } else if (cellValue === 2) {
        return '客户';
      } else if (cellValue === 3) {
        return '商户';
      } else if (cellValue === 4) {
        return '服务员';
      } else if (cellValue === 5) {
        return '业务员';
      }
    },
    formatUserRoles(cellValue) {
      if (cellValue === 1) {
        return 'success';
      } else if (cellValue === 2) {
        return '';
      } else if (cellValue === 3) {
        return 'warning';
      } else if (cellValue === 4) {
        return 'info';
      } else if (cellValue === 5) {
        return 'danger';
      }
    },
    formatState(cellValue) {
      if (cellValue === 0) {
        return '禁用';
      } else if (cellValue === 1) {
        return '启用';
      }
    },
    formatStates(cellValue) {
      if (cellValue === 0) {
        return 'warning';
      } else if (cellValue === 1) {
        return 'success';
      }
    },
    formatLogin(cellValue) {
      if (cellValue === 0 || cellValue === '') {
        return '离线';
      } else if (cellValue === 1) {
        return '在线';
      }
    },
    formatLogins(cellValue) {
      if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return 'success';
      }
    },
    listTable() {
      let data = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        userName: this.searchForm.userName,
        nickName: this.searchForm.nickName,
        phone: this.searchForm.phone,
        userRole: this.searchForm.userRole,
        state: this.searchForm.state,
        isLogin: this.searchForm.isLogin,
      };
      this.fetchData(data);
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listTable();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listTable();
    },
    handleClickEditor(row) {
      this.$router.push({ path: '/sys/userEdit', query: { id: row.userId } });
    },
    handleClickDetail(row) {
      this.$router.push({ path: '/sys/userDetail', query: { id: row.userId } });
    },
    handleClickResetPass(row) {
      this.$confirm('确定重置该用户登录密码吗？', message.TITLE_PROMPT, {}).then(() => {
        AuthApi.resetUserPwd({ userId: row.userId }).then((res) => {
          this.$Utils.notifySuccess('重置密码成功');
        });
      });
    },
    handleClickAdd() {
      this.$router.push({ path: '/sys/userAdd' });
    },
    handleIsDisable(row) {
      let currentState = row.state === 0 ? 1 : 0;
      let newStateName = row.state === 0 ? message.MSG_CONFIRM_ENABLE : message.MSG_CONFIRM_DISABLE;
      this.$confirm(newStateName, message.TITLE_PROMPT, {}).then(() => {
        let data = {
          userId: row.userId,
          loginType: 1,
          state: currentState,
        };
        AuthApi.updateUserState(data).then((res) => {
          row.state = currentState;
          this.$Utils.notifySuccess();
        });
      });
    },
    handleClickDelete(row) {
      this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        let data = {
          id: row.userId,
          state: -1,
        };
        AuthApi.deleteUser(data).then((res) => {
          this.listTable();
          this.$Utils.notifySuccess();
        });
      });
    },
    fetchData(data) {
      this.$emit('show-loading', true);
      AuthApi.listUser(data)
        .then((res) => {
          this.tableList = res.data.list;
          this.page.pageTotal = res.data.total;
          this.$emit('show-loading', false);
        })
        .catch((error) => {
          this.$emit('show-loading', false);
        });
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listTable();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch();
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
@import '@/assets/css/views/add.scss';
</style>
